// 导入 http 模块
import http from 'wechat-http'
//配置基地址
http.baseURL = 'https://live-api.itheima.net'

//请求拦截器
http.intercept.request = ((params) => {
  const token = getApp().token
  if (token) {
    params.header = {
      Authorization: `Bearer ${token}`,
      ...params.header
    }
  }
  return params
})

//添加响应拦截器
http.intercept.response = (async (res) => {
  const app = getApp()
  //token失效
  if (res.data.code === 401) {
    //token过期，刷新token过期跳转登录页面
    if (res.config.url.includes('/refreshToken')) {
      wx.utils.toast('请重新登录')
      const currentPage = getCurrentPages()
      //获取页面历史路径
      const lastPage = currentPage[currentPage.length - 1].route
      return wx.redirectTo({
        url: '/pages/login/index?redirect=' + lastPage,
      })
    }
    if(!app.r_token) return
    //刷新token
    const Res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: `Bearer ${app.r_token}`
      }
    })
    //保存新的token
    app.setToken(Res.data.token, Res.data.refreshToken)
    //无感刷新
    res.config.header = {
      Authorization: `Bearer ${app.token}`
    }
    console.log(res.config.header)


    return http(res.config)
  } else if (res.data.code !== 10000) {
    wx.showToast({
      title: res.data.message,
      icon: 'error',
      mask: true
    })
    return Promise.reject(res)
  }
  return res.data
})
//挂载到wx全局对象
wx.http = http
export default http